package com.fzb.forum4j.controller;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fzb.forum4j.po.User;
import com.fzb.forum4j.po.UserDetails;
import com.fzb.forum4j.service.api.IUserService;
import com.fzb.forum4j.util.Mail;
import com.fzb.forum4j.util.ParseTools;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.validator.validators.EmailValidator;

@Controller("userAction")
@Scope("prototype")
public class UserAction extends CommonsAction<User>{

	/**
	 * 负责用户的操作
	 */
	private static final long serialVersionUID = 1L;
	@Resource(name="userServiceImpl")
	private IUserService userService;
	
	
	public String login(){
		if(userService.login(getQmd()))
		{
			setAttrToSession("userMsg",getQmd().getT());
			Cookie cookie=new Cookie("fid", ParseTools.encodeBase64(getT().getUserName()+","+getT().getPassword()));
			cookie.setMaxAge(60*60*24);
			cookie.setPath("/");
			ServletActionContext.getResponse().addCookie(cookie);
			
			//检查是否有人@
			userService.getMessageByUserId(getQmd());
			getRequest().getSession().setAttribute("messages", getQmd().getData().get("messages"));
			return "go_forward";
		}
		else{
			return cancel();
		}
	}
	
	/**不清空cookie 中的用户信息
	 * @return
	 */
	public String logout(){
		ActionContext.getContext().getSession().clear();
		ActionContext.getContext().getSession().put("userStatus", "logout");
		return "login";
	}
	
	/**清空cookie 并且移除session 中的用户信息
	 * @return
	 */
	public String cancel(){
		ActionContext.getContext().getSession().remove("userMsg");
		Cookie[] cs=getRequest().getCookies();
		if(cs!=null){
			for(Cookie cookie:cs){
				if(cookie.getName().equals("fid")){
					cookie.setMaxAge(0);
					ServletActionContext.getResponse().addCookie(cookie);
				}
			}
		}
		return "login";
	}
	
	public String autoLogin(){
		validateLogin();
		login();
		return "goBack";
	}
	
	public String home(){
		if(getUserMsg()!=null){
			if(getUserMsg().getUserName().equals(getQmd().getT().getUserName()) || getQmd().getT().getUserName()==null){
				getQmd().setT(getUserMsg());
			}
		}
		userService.getBlogHomeData(getQmd());
		getRequest().setAttribute("rurl", getContextPath()+"u/"+getT().getUserName()+"/blog");
		return "home";
	}
	
	public Boolean loginFormCookie() {
		Cookie[] cs=getRequest().getCookies();
		if(cs!=null){
			for(Cookie cookie:cs){
				if(cookie.getName().equals("fid")){
					String str[]=ParseTools.decodeBase64(cookie.getValue()).split(",");
					if(str.length==2){
						if(getT()!=null && str[0].equals(getT().getUserName())){
							getT().setUserName(str[0]);
							getT().setPassword2(str[1]);
							return true;
						}
						else if(getRequest().getSession().getAttribute("autoLogin")!=null){
							getT().setUserName(str[0]);
							getT().setPassword2(str[1]);
							return true;
						}
					}
				}	
			}
		}
		if(getT().getUserName()==null || getT().getUserName().length()==0){
			return false;
		}
		if(getT().getPassword()==null || getT().getPassword().length()==0){
			return false;
		}
		return true;
		
	}
	public void validateLogin(){
		if(!loginFormCookie()){
			addFieldError("error", "请检查用户名或者密码");
		}
		
	}
	
	public String go_register(){
		return "register";
	}
	public String checkUserNameExists(){
		if(userService.loadUserByUserName(getQmd().getT().getUserName())!=null){
			getData().put("userNamestatus", true);
		}
		else{
			getData().put("userNamestatus", false);
		}
		return "json";
	}
	
	public String register(){
		
		//查询用户名是否存在 
		checkUserNameExists();
		if(!(Boolean)getData().get("userNamestatus")){
			//初始用户注册信息
			UserDetails du=new UserDetails();
			du.setIcon(0);
			du.setUser(getT());
			du.setTemplate("template/default/blog/style/1");
			du.setHeaderFileName("gravatar.jpg");
			getT().setNickName(getT().getUserName());
			getT().setDetails(du);
			getT().setRegTime(new Date());
			getT().setUserName(getT().getUserName().toLowerCase());
			getT().setUserEmail(getT().getUserEmail().toLowerCase());
			if(add().equals("add_success")){
				try{
					String encodeBase64Str=ParseTools.encodeBase64(new Date().getTime());		
					getRequest().getSession().setAttribute(encodeBase64Str, "b_Email,"+getT().getUserName());
					getRequest().getSession().setAttribute("bEmail_key", encodeBase64Str);
					ServletActionContext.getRequest().getSession().setMaxInactiveInterval(60*60*24);
					bMailToUser(encodeBase64Str);
					return "add_success";
				}	
				catch (Exception e) {
					return "add_success";
				}
			}
		}
		else{
			addFieldError("userName", "用户名应经存在");
		}
		return INPUT;
		
	
	}
	
	public void validateRegister(){
		clearFieldErrors();
		if(getT().getUserName()==null || (getT().getUserName().length()<=3)){
			addFieldError("userName", "用户名不能为空或者小于3位");
		}
		if(getT().getPassword()==null || getT().getPassword().length()<=6){
			addFieldError("password", "密码不能为空或小于6位");
		}
		else if(getT().getUserEmail()!=null  && !getT().getUserEmail().matches(EmailValidator.EMAIL_ADDRESS_PATTERN)){
			addFieldError("userEmail", "请检查邮箱地址");
		}
	}
	
	public String validateEmial(){
		return "validate_success";
	}
	public String bEmail(){
		if(ActionContext.getContext().getSession().get(getT().getKey())!=null){
			getT().setUserName(ActionContext.getContext().getSession().get(getT().getKey()).toString());
			
			return "bEmai_success";
		}
		else{
			return  "outOfDate";
		}
		
	}
	
	public String updatePwd(){
		return super.modify();
	}
	public String forgetPwd(){
		return "forgetPwd";
	}
 
	public String findPwd(){
		if(ActionContext.getContext().getSession().get(getT().getKey())!=null){
			
			getT().setUserName(ActionContext.getContext().getSession().get(getT().getKey()).toString());
			return "findPwd";
		}
		else{
			return  "outOfDate";
		}
	}
	
	public String lostFoundPwd(){
		if(ActionContext.getContext().getSession().get(getT().getKey())!=null){
			String nPwd=getT().getPassword();
			getT().setUserName(ActionContext.getContext().getSession().get(getT().getKey()).toString());
			setT(userService.loadUserByUserName(getT().getUserName()));
			getT().setPassword(nPwd);
			super.modify();
			return "lostFoundPwd_success";
		}
		else{
			return "lostFoundPwd_failed";
		}
	}
	
	public String mailTo(){
		Boolean status=userService.existsUserNameAndEmail(getT());
		if(status){
			String key=ParseTools.encodeBase64(new Date().getTime());
			ServletActionContext.getRequest().getSession().setAttribute(key,getT().getUserName());
			ServletActionContext.getRequest().getSession().setMaxInactiveInterval(60*60*24);
			
			Mail mail=new Mail(getWebSite(),getT().getUserEmail(),"findPassword", getHomePage()+"/user/findPwd?t.key="+key,"找回密码");
			mail.sendMail();
		}
		return "mailTo_success";
	}
	
	public String bMailToUser(String encodeBase64Str){
		Boolean status=true;
		if(status){
			System.out.println(getHomePage()+"/user/bEmail?t.key="+encodeBase64Str);
			Mail mail=new Mail(getWebSite(),getT().getUserEmail(),"bEmail", getHomePage()+"/user/bEmail?t.key="+encodeBase64Str,"激活用户");
			mail.sendMail();
		}
		return "mailTo_success";
	}
	
	public void validateMailTo(){
		if(getT().getUserEmail()==null && getT().getUserEmail().length()==0){
			addActionError("邮箱不能为空");
		}
		if(getT().getUserName()==null && getT().getUserName().length()==0){
			addActionError("邮箱不能为空");
		}
	}
	@Override
	public String list() {
		userService.getList(getQmd());
		return "json";
	}
	@Override
	public String del() {
		return "403";
	}
	
	public String messageCentre(){
		return "messageCentre";
	}
	
	public String admin(){
		return "manage";
	}
}
